import os.path
from config.configs import TEST_PORT, TEST_DB_HOST, DATA_PATH
from tools.mongo_tool import MongoDbLink
import json
from bson import json_util
from tools.tool import read_json_file, create_balance_datas


def reset_bonded():
    """重置保税全部数据"""
    bs = MongoDbLink(TEST_DB_HOST, TEST_PORT, db_name='bonded20231023')
    bs.delete_many(doc='stocks', cond={})
    bs.delete_many(doc='orders', cond={})
    bs.delete_many(doc='stocktransfers', cond={})
    bs.delete_many(doc='settlements', cond={})
    bs.delete_many(doc='balancerecords', cond={})
    bs.delete_many(doc='withdraws', cond={})
    bs.update_many(doc='balances', cond={}, update={"$set": {"balance": 0}})
    bs.close()


def reset_workflow():
    """重置workflow全部数据（除采购单）"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, db_name='workflow_dev')
    wf.delete_many(doc='costs', cond={})
    wf.delete_many('transfer', {})
    wf_clean_stocks()
    wf_clean_settlement()
    wf_clean_orders()
    wf.update_many('autoincrements', {}, {"$set": {"timestamp": 0}})
    wf.close()


def bs_clean_settlement():
    """清除保税订单结算、提现申请数据、仓储费数据、重置账户余额"""
    bs = MongoDbLink(TEST_DB_HOST, TEST_PORT, db_name='bonded20231023')
    bs_clean_transfer()
    bs.delete_many(doc='settlements', cond={})
    bs.update_many(doc='orders', cond={"merchantStmtStatus": {"$in": ["finish", "return"]}},
                   update={"$set": {"merchantStmtStatus": "pending"}})
    bs.delete_many(doc='balancerecords', cond={})
    bs.update_many(doc='balances', cond={}, update={"$set": {"balance": 0}})
    bs.delete_many(doc='withdraws', cond={})
    bs.close()


def bs_clean_transfer():
    """清除保税划拨销售数据"""
    bs = MongoDbLink(TEST_DB_HOST, TEST_PORT, db_name='bonded20231023')
    bs.delete_many(doc='stocks', cond={"source": "transfer"})
    bs.delete_many(doc='stocktransfers', cond={})
    bs.delete_many(doc='orders', cond={"saleType": "transfer"})
    bs.delete_many(doc='settlements', cond={"stmtFees": []})
    bs.delete_many(doc='balancerecords', cond={"cause": "transfer_income"})
    bs.update_many(doc='balances', cond={"currency": "CNY"}, update={"$set": {"balance": 0}})
    bs.close()


def bs_clean_stockfee():
    """清除保税仓储费数据"""
    bs = MongoDbLink(TEST_DB_HOST, TEST_PORT, db_name='bonded20231023')
    bs.delete_many(doc='settlements', cond={"stmtType": "storage"})
    bs.delete_many(doc='balancerecords', cond={"cause": "storage"})
    bs.close()


def wf_clean_settlement():
    """清除workflow结算数据，重置渠道资金期初余额"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    wf.delete_many(doc='balancerecords', cond={})
    wf.delete_many(doc='settlements', cond={})
    wf.delete_many(doc='payments', cond={})
    wf.delete_many(doc='balances', cond={"channelName": "海外渠道-炜哥", "currencyType": {"$nin": ["CNY", "USD"]}})
    wf.delete_many(doc='balances', cond={"channelName": "DE线路", "currencyType": {"$ne": "EUR"}})
    wf.delete_many(doc='balances', cond={"channelName": "CN线路", "currencyType": {"$ne": "CNY"}})
    wf.update_many(doc='balances', cond={"channelName": "海外渠道-炜哥"}, update={"$set": {"amount": 160000}})
    wf.update_many(doc='balances', cond={"channelName": "DE线路"}, update={"$set": {"amount": 80000}})
    wf.update_many(doc='balances', cond={"channelName": "CN线路"}, update={"$set": {"amount": 1000000}})
    wf.update_many('autoincrements', {"type": {"$in": [5, 7]}}, {"$set": {"timestamp": 0}})
    wf.close()


def wf_clean_stocks():
    """清除workflow全部库存数据"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    wf.delete_many(doc="stocks", cond={})
    wf.delete_many(doc='stockinorders', cond={})
    wf.delete_many(doc='costs', cond={})
    wf.update_many('autoincrements', {"type": {"$in": [0, 2]}}, {"$set": {"timestamp": 0}})
    wf.close()


def wf_clean_orders():
    """清除workflow全部订单数据"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    wf.delete_many(doc='orders', cond={})
    wf.delete_many(doc='suborders', cond={})
    wf.delete_many(doc='returnorders', cond={})
    wf.delete_many(doc='jointreturnorders', cond={})
    wf.delete_many(doc='jointsuborders', cond={})
    wf.update_many('autoincrements', {"type": {"$in": [1, 3, 4, 6]}}, {"$set": {"timestamp": 0}})
    wf.close()


def wf_clean_jw_orders():
    """清除workflow集物订单数据"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    wf.delete_many(doc='orders', cond={"salesChannelName": {"$regex": "集物"}})
    wf.delete_many(doc='suborders', cond={"salesChannelName": {"$regex": "集物"}})
    wf.delete_many(doc='returnorders', cond={"salesChannelName": {"$regex": "集物"}})
    wf.update_many('autoincrements', {"type": {"$in": [3, 4, 6]}}, {"$set": {"timestamp": 0}})
    wf.close()


def wf_clean_jw_settlement():
    """清除workflow全部结算数据，重置渠道资金期初余额"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    wf.delete_many(doc='balancerecords', cond={})
    wf.delete_many(doc='settlements', cond={})
    wf.delete_many(doc='balances', cond={"channelName": "海外渠道-炜哥", "currencyType": {"$nin": ["CNY", "USD"]}})
    wf.delete_many(doc='balances', cond={"channelName": "DE线路", "currencyType": {"$ne": "EUR"}})
    wf.delete_many(doc='balances', cond={"channelName": "CN线路", "currencyType": {"$ne": "CNY"}})
    wf.update_many(doc='balances', cond={"channelName": "海外渠道-炜哥"}, update={"$set": {"amount": 160000}})
    wf.update_many(doc='balances', cond={"channelName": "DE线路"}, update={"$set": {"amount": 80000}})
    wf.update_many(doc='balances', cond={"channelName": "CN线路"}, update={"$set": {"amount": 1000000}})
    wf.update_many('autoincrements', {"type": {"$in": [5, 7]}}, {"$set": {"timestamp": 0}})
    wf.close()


def wf_clean_bs_orders():
    """清除workflow保税订单数据"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    wf.delete_many(doc='orders', cond={"salesChannelName": {"$regex": "保税仓"}})
    wf.delete_many(doc='suborders', cond={"salesChannelName": {"$regex": "保税仓"}})
    wf.delete_many(doc='returnorders', cond={"salesChannelName": {"$regex": "保税仓"}})
    wf.delete_many(doc='jointreturnorders', cond={})
    wf.delete_many(doc='jointsuborders', cond={})
    wf.update_many('autoincrements', {"type": {"$in": [1]}}, {"$set": {"timestamp": 0}})
    wf.close()


def wf_clean_bs_stocks():
    """清除workflow保税库存数据"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    wf.delete_many(doc="stocks", cond={"warehouseName": {"$regex": "保税仓"}})
    wf.delete_many(doc='stockinorders', cond={"warehouseName": {"$regex": "保税仓"}})
    wf.update_many('autoincrements', {"type": {"$in": [0]}}, {"$set": {"timestamp": 0}})
    wf.close()


def wf_clean_jointPurchase_datas():
    """清除workflow合资订单和结算数据"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    joint_order_list = [i['outerOrderNo'] for i in wf.find('suborders', {"appointNo": "AP2309199715782"})]
    wf.delete_many('orders', {"outerOrderNos": {"$in": joint_order_list}})
    wf.delete_many('returnorders', {"outerReturnOrderNo": {"$in": joint_order_list}})
    wf.delete_many('suborders', {"outerOrderNo": {"$in": joint_order_list}})
    wf.delete_many('settlements', {"outerOrderNo": {"$in": joint_order_list}})
    wf.delete_many('balancerecords', {"outerOrderNo": {"$in": joint_order_list}})
    wf.delete_many('balancerecords', {"outerReturnOrderNo": {"$in": joint_order_list}})


def back_up_jw_balances():
    jw = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'alpha-test')
    origin_balances = jw.find(doc='balances', cond={})
    li = []
    [li.append(i) for i in origin_balances]
    with open('../data/jw_backup_balances.json', 'w', encoding='utf8') as f:
        f.write('[')
        for i in range(len(li)):
            if i != len(li) - 1:
                json.dump(li[i], f, default=json_util.default, ensure_ascii=False, indent=2)
                f.write(',\n')
            else:
                json.dump(li[i], f, default=json_util.default, ensure_ascii=False, indent=2)
        f.write(']')


def reset_jw_balances():
    bs = MongoDbLink(TEST_DB_HOST, TEST_PORT, db_name='alpha-test')
    # back_up_jw_balances()
    bs.delete_many('balances', {})
    data = os.path.join(DATA_PATH, 'jw_backup_balances.json')
    payload = read_json_file(data)
    bs.insert_many('balances', payload)


def jw_clean_settlements():
    """清除集物结算数据"""
    jw = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'alpha-test')
    jw.delete_many(doc='dewustatements', cond={"createdAt": {"$gt": 1704855694392}})
    jw.delete_many(doc='dewustatementreturns', cond={"createdAt": {"$gt": 1704857434392}})
    jw.delete_many(doc='balancerecords', cond={"createdAt": {"$gt": 1704855694392}})


def clean_joint_datas(createdAt):
    """清除指定时间后上传的合资订单销售和退货结算、balancerecords数据，恢复账户余额"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    settlement_orders, amount_list, origin_balance = [], [], 0
    pipeline = [{
        "$lookup": {"from": "jointsuborders",
                    "localField": "outerOrderNo",
                    "foreignField": "outerOrderNo",
                    "as": "result"}
    },
        {
            "$match": {"result": {"$ne": []},
                       "createdAt": {"$gte": createdAt}}
        },
        {
            "$unwind": {"path": "$result"}
        },
        {
            "$project": {"_id": 0, "orderNo": "$result.outerOrderNo"}
        }]
    for i in wf.aggregate('suborders', pipeline=pipeline):
        settlement_orders.append(i['orderNo'])
    [amount_list.append(i['settlementAmount']) for i in wf.find('settlements',
                                                                {"outerOrderNo": {"$in": settlement_orders}})]
    amount = sum(amount_list)
    wf.delete_many('orders', {"outerOrderNos": {"$in": settlement_orders}})
    wf.delete_many('suborders', {"outerOrderNo": {"$in": settlement_orders}})
    wf.delete_many('returnorders', {"outerReturnOrderNo": {"$in": settlement_orders}})
    wf.delete_many('settlements', {"outerOrderNo": {"$in": settlement_orders}})
    wf.delete_many('balancerecords', {"outerOrderNo": {"$in": settlement_orders}})
    for i in wf.find('balances', {"channelName": "海外渠道-炜哥", "currencyType": "USD"}):
        origin_balance += i['amount']
    wf.update_one('balances', {"channelName": "海外渠道-炜哥", "currencyType": "USD"},
                  {"$set": {"amount": origin_balance - amount}})


def correct_balance():
    """矫正workflow账户余额"""
    wf = MongoDbLink(TEST_DB_HOST, TEST_PORT, 'workflow_dev')
    origin_list, balance_list = [], []
    origin = wf.aggregate('channels', [{
        "$unwind": {
            "path": "$originCurrency",
        },
    },
        {
            "$group": {
                "_id": {
                    "channelName": "$name",
                    "currencyType": "$originCurrency.currencyType",
                },
                "amount": {
                    "$avg": "$originCurrency.amount",
                },
            },
        },
        {
            "$project": {
                "currencyType": "$_id.currencyType",
                "channelName": "$_id.channelName",
                "amount": 1,
                "_id": 0,
            },
        },
    ])
    for z in origin:
        origin_list.append(z)
    balance = wf.aggregate('balancerecords', [{
        "$group": {
            "_id": {
                "channelName": "$channelName",
                "currency": "$currency",
            },
            "amount": {
                "$sum": "$amount",
            },
        },
    },
        {
            "$project":
                {
                    "currencyType": "$_id.currency",
                    "channelName": "$_id.channelName",
                    "amount": 1,
                    "_id": 0,
                },
        },
    ])
    for z in balance:
        balance_list.append(z)
    for i in balance_list:
        if wf.count_documents('channels', {'name': i['channelName'], 'originCurrency.currencyType': i[
            'currencyType']}) == 0 and wf.count_documents('balances', {'channelName': i['channelName'],
                                                                       'currencyType': i['currencyType']}) == 1:
            wf.update_one('balances', {'channelName': i['channelName'], 'currencyType': i['currencyType']},
                          {"$set": {'amount': i['amount']}})
        elif wf.count_documents('channels', {'name': i['channelName'], 'originCurrency.currencyType': i[
            'currencyType']}) == 0 and wf.count_documents('balances', {'channelName': i['channelName'],
                                                                       'currencyType': i['currencyType']}) == 0:
            payload = create_balance_datas(1, i['channelName'], i['currencyType'], i['amount'])
            collection_payload = payload[1]
            array_payload = payload[0]
            wf.insert('balances', collection_payload)
            wf.aggregate('channels', [{"$project": {'balance': {"$concatArrays": ["$balance", array_payload]}}}])
        else:
            for z in origin_list:
                if z['channelName'] == i['channelName'] and z['currencyType'] == i['currencyType']:
                    origin_amount = z['amount']
                    wf.update_one('balances', {'channelName': i['channelName'], 'currencyType': i['currencyType']},
                                  {'$set': {
                                      'amount': origin_amount + i['amount']
                                  }})
